<template>
  <div class="user-management">
    <div class="header">
      <h2>用户权限管理</h2>
      <n-button type="primary" @click="showAddUserModal = true">
        <template #icon>
          <n-icon><PersonAdd /></n-icon>
        </template>
        添加用户
      </n-button>
    </div>

    <!-- 用户列表 -->
    <n-data-table
      :columns="columns"
      :data="users"
      :loading="loading"
      :pagination="pagination"
      :row-key="row => row.username"
    />

    <!-- 添加用户对话框 -->
    <n-modal v-model:show="showAddUserModal" preset="dialog" title="添加用户">
      <template #default>
        <n-form ref="addUserFormRef" :model="newUser" :rules="addUserRules">
          <n-form-item label="用户名" path="username">
            <n-input v-model:value="newUser.username" placeholder="请输入用户名" />
          </n-form-item>
          <n-form-item label="角色" path="role">
            <n-select v-model:value="newUser.role" :options="roleOptions" />
          </n-form-item>
          <n-form-item label="描述" path="description">
            <n-input v-model:value="newUser.description" placeholder="可选，用户描述信息" />
          </n-form-item>
        </n-form>
      </template>
      <template #action>
        <n-space>
          <n-button @click="showAddUserModal = false">取消</n-button>
          <n-button type="primary" @click="handleAddUser" :loading="addUserLoading">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 编辑用户权限对话框 -->
    <n-modal v-model:show="showEditModal" preset="dialog" title="修改用户权限">
      <template #default>
        <n-form ref="editFormRef" :model="editingUser" :rules="editUserRules">
          <n-form-item label="用户名">
            <n-input :value="editingUser.username" readonly />
          </n-form-item>
          <n-form-item label="新角色" path="role">
            <n-select v-model:value="editingUser.role" :options="roleOptions" />
          </n-form-item>
        </n-form>
      </template>
      <template #action>
        <n-space>
          <n-button @click="showEditModal = false">取消</n-button>
          <n-button type="primary" @click="handleUpdateUser" :loading="updateUserLoading">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { 
  NDataTable, 
  NButton, 
  NTag, 
  NIcon, 
  NSpace, 
  NModal, 
  NForm, 
  NFormItem, 
  NInput, 
  NSelect,
  useMessage,
  useDialog
} from 'naive-ui'
import { PersonAdd, CreateOutline, TrashOutline } from '@vicons/ionicons5'

const message = useMessage()
const dialog = useDialog()

// 响应式数据
const users = ref([])
const loading = ref(false)
const showAddUserModal = ref(false)
const showEditModal = ref(false)
const addUserLoading = ref(false)
const updateUserLoading = ref(false)

// 新用户表单
const newUser = reactive({
  username: '',
  role: 'user',
  description: ''
})

// 编辑用户表单
const editingUser = reactive({
  username: '',
  role: ''
})

// 表单引用
const addUserFormRef = ref(null)
const editFormRef = ref(null)

// 角色选项
const roleOptions = [
  { label: '普通用户', value: 'user' },
  { label: '管理员', value: 'admin' },
  { label: '系统管理员', value: 'system' }
]

// 表单验证规则
const addUserRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 50, message: '用户名长度应在2-50个字符之间', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const editUserRules = {
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50],
  onChange: (page) => {
    pagination.page = page
  },
  onUpdatePageSize: (pageSize) => {
    pagination.pageSize = pageSize
    pagination.page = 1
  }
})

// 表格列配置
const columns = [
  {
    title: '用户名',
    key: 'username',
    width: 200
  },
  {
    title: '角色',
    key: 'role',
    width: 120,
    render(row) {
      const roleMap = {
        'system': { type: 'error', text: '系统管理员' },
        'admin': { type: 'warning', text: '管理员' },
        'user': { type: 'info', text: '普通用户' }
      }
      const roleInfo = roleMap[row.role] || { type: 'default', text: row.role }
      return h(NTag, { type: roleInfo.type }, { default: () => roleInfo.text })
    }
  },
  {
    title: '描述',
    key: 'description',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '状态',
    key: 'active',
    width: 100,
    render(row) {
      return h(NTag, { 
        type: row.active ? 'success' : 'default' 
      }, { 
        default: () => row.active ? '活跃' : '禁用' 
      })
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 160,
    render(row) {
      return h(NSpace, { size: 'small' }, {
        default: () => [
          h(NButton, {
            size: 'tiny',
            type: 'primary',
            onClick: () => handleEditUser(row)
          }, {
            default: () => '编辑',
            icon: () => h(NIcon, { size: 14 }, { default: () => h(CreateOutline) })
          }),
          h(NButton, {
            size: 'tiny',
            type: 'error',
            onClick: () => handleDeleteUser(row)
          }, {
            default: () => '删除',
            icon: () => h(NIcon, { size: 14 }, { default: () => h(TrashOutline) })
          })
        ]
      })
    }
  }
]

// API 调用函数
const fetchUsers = async () => {
  loading.value = true
  try {
    console.log('开始获取用户列表...')
    const response = await fetch('/api/users', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
      }
    })
    console.log('API响应状态:', response.status)
    const result = await response.json()
    console.log('API响应数据:', result)
    
    if (result.success) {
      users.value = result.data
      console.log('设置用户数据:', users.value)
    } else {
      message.error(result.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleAddUser = async () => {
  try {
    await addUserFormRef.value?.validate()
    addUserLoading.value = true
    
    const response = await fetch('/api/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
      },
      body: JSON.stringify({
        username: newUser.username.trim(),
        role: newUser.role,
        description: newUser.description.trim()
      })
    })
    
    const result = await response.json()
    
    if (result.success) {
      message.success('用户添加成功')
      showAddUserModal.value = false
      // 重置表单
      Object.assign(newUser, {
        username: '',
        role: 'user',
        description: ''
      })
      // 刷新用户列表
      await fetchUsers()
    } else {
      message.error(result.message || '添加用户失败')
    }
  } catch (error) {
    console.error('添加用户失败:', error)
    message.error('添加用户失败')
  } finally {
    addUserLoading.value = false
  }
}

const handleEditUser = (user) => {
  editingUser.username = user.username
  editingUser.role = user.role
  showEditModal.value = true
}

const handleUpdateUser = async () => {
  try {
    await editFormRef.value?.validate()
    updateUserLoading.value = true
    
    const response = await fetch('/api/users/role', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
      },
      body: JSON.stringify({
        username: editingUser.username,
        role: editingUser.role
      })
    })
    
    const result = await response.json()
    
    if (result.success) {
      message.success('用户权限更新成功')
      showEditModal.value = false
      // 刷新用户列表
      await fetchUsers()
    } else {
      message.error(result.message || '更新用户权限失败')
    }
  } catch (error) {
    console.error('更新用户权限失败:', error)
    message.error('更新用户权限失败')
  } finally {
    updateUserLoading.value = false
  }
}

const handleDeleteUser = (user) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        const response = await fetch(`/api/users/${user.username}`, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('authToken')}`
          }
        })
        
        const result = await response.json()
        
        if (result.success) {
          message.success('用户删除成功')
          // 刷新用户列表
          await fetchUsers()
        } else {
          message.error(result.message || '删除用户失败')
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        message.error('删除用户失败')
      }
    }
  })
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}
</style>